package com.shuai.web.servlet;

import com.shuai.dao.StudentDao;
import com.shuai.domain.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取请求参数
       /* String username = request.getParameter("username");
        String password = request.getParameter("password");
        //3.封装Student对象
        Student loginStudent = new Student();
        loginStudent.setusername(username);
        loginStudent.setPassword(password);*/
        Map<String, String[]> parameterMap = request.getParameterMap();
        Student loginStudent = new Student();
        try {
            BeanUtils.populate(loginStudent,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //4.调用StudentDao的login方法
        StudentDao studentDao = new StudentDao();
        Student student = studentDao.login(loginStudent);
        //5.判断student
        if (student == null){
            request.getRequestDispatcher("/failServlet").forward(request,response);  //转发
        }else{
            //存储 数据
            request.setAttribute("student",student);
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }

    }
}
